package com.ptszyxx.popose.module.main;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;

import com.ptszyxx.popose.BuildConfig;
import com.ptszyxx.popose.MyApp;
import com.ptszyxx.popose.common.utils.YActivityUtil;
import com.ptszyxx.popose.common.utils.YChatUtil;
import com.ptszyxx.popose.common.utils.YLoginUtil;
import com.ysg.base.BaseViewModel;
import com.ysg.bus.RxBus;
import com.ysg.bus.RxSubscriptions;
import com.ysg.bus.event.SingleLiveEvent;
import com.ysg.event.LogoutEvent;
import com.ysg.http.BaseResponse;
import com.ysg.http.HttpUtils;
import com.ysg.http.callback.OnErrorResult;
import com.ysg.http.callback.OnSuccessResult;
import com.ysg.http.data.CommonRepository;
import com.ysg.http.data.entity.im.ImSignEntity;
import com.ysg.http.data.entity.mine.UserConfigEntity;
import com.ysg.http.data.entity.mine.VersionEntity;
import com.ysg.http.data.entity.mine.VipResult;
import com.ysg.http.data.entity.ticket.TicketEntity;
import com.ysg.http.data.entity.user.UserResult;
import com.ysg.utils.YChannelUtil;
import com.ysg.utils.YConfigUtil;
import com.ysg.utils.YSPUtils;
import com.ysg.utils.YStringUtil;
import com.ysg.utils.YUserUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class MainVM extends BaseViewModel<CommonRepository> {

    public MainVM(@NonNull Application application, CommonRepository model) {
        super(application, model);
    }

    public UIChangeObservable uc = new UIChangeObservable();

    public class UIChangeObservable {
        public SingleLiveEvent onImSignEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onUpdateVersionEvent = new SingleLiveEvent<>();
    }

    //TODO 3.异步通知处理=====================
    public Disposable disposable;

    @Override
    public void registerRxBus() {
        super.registerRxBus();
        disposable = RxBus.getDefault().toObservable(LogoutEvent.class)
                .subscribe(new Consumer<LogoutEvent>() {
                    @Override
                    public void accept(LogoutEvent event) {
                        YLoginUtil.getInstance().logout(MyApp.getContext());
                    }
                });
    }

    @Override
    public void removeRxBus() {
        super.removeRxBus();
        RxSubscriptions.remove(disposable);
    }


    /**
     * 腾讯IM的签名
     */
    public void requestImSign() {
        Map<String, String> map = new HashMap<>();
        HttpUtils.getInstance()
                .data(model.imSign(map), this,
                        new OnSuccessResult<ImSignEntity>() {
                            @Override
                            public void onSuccessResult(BaseResponse<ImSignEntity> response) {
                                ImSignEntity imSign = response.getData();
                                YChatUtil.getInstance().login(imSign.getLogincode(), imSign.getUserSig(), imSign.getAppid(), new YChatUtil.OnIMListener() {
                                    @Override
                                    public void onSuccess() {
                                        uc.onImSignEvent.call();
                                    }

                                    @Override
                                    public void onError() {
                                        YLoginUtil.getInstance().logout(getApplication());
                                    }
                                });
                            }
                        }, new OnErrorResult() {
                            @Override
                            public void onErrorResult(int code, String msg) {
                                YLoginUtil.getInstance().logout(getApplication());
                            }
                        });
    }

    /**
     * 版本
     */
    public void requestVersion() {
        Map<String, String> map = new HashMap<>();
        map.put("qudaoid", "3");
        map.put("verint", String.valueOf(BuildConfig.VERSION_CODE));
        HttpUtils.getInstance()
                .data(model.versionInfo(map), this, new OnSuccessResult<VersionEntity>() {
                    @Override
                    public void onSuccessResult(BaseResponse<VersionEntity> response) {
                        uc.onUpdateVersionEvent.setValue(response.getData());
                    }
                });
    }

    /**
     * vip列表
     */
    public void requestVip() {
        Map<String, String> map = new HashMap<>();
        HttpUtils.getInstance()
                .data(model.vip(map), this, new OnSuccessResult<VipResult>() {
                    @Override
                    public void onSuccessResult(BaseResponse<VipResult> response) {
                        VipResult vipResult = response.getData();
                        if (vipResult != null && vipResult.getUser() != null) {
                            YUserUtil.saveVip(vipResult.getUser().getIsVip());
                        }
                    }
                });
    }

    /**
     * 客服,VIP开关
     */
    public void requestSetup() {
        Map<String, String> map = new HashMap<>();
        HttpUtils.getInstance()
                .data(model.setup(map), this,
                        new OnSuccessResult<UserConfigEntity>() {
                            @Override
                            public void onSuccessResult(BaseResponse<UserConfigEntity> response) {
                                YSPUtils.getInstance().saveUserConfig(response.getData());
                            }
                        });
    }

    /**
     *
     */
    public void requestTicketConfig() {
        String ticket = YConfigUtil.getTicket();
        if (YStringUtil.eq(1, ticket)) {
            requestTicket(false, false);
        } else if (YStringUtil.eq(2, ticket)) {
            ticketCountTime();
        } else if (YStringUtil.eq(21, ticket)) {
            requestTicket(true, false);
        }
    }

    /**
     * 门票倒计时
     */
    private Disposable mDisposable;

    public void ticketCountTime() {
        int countTime = YConfigUtil.getTicketTime();
        if (mDisposable == null || mDisposable.isDisposed()) {
            Observable.interval(0, 1, TimeUnit.SECONDS)
                    .take(countTime + 1)// 设置总共发送的次数
                    .map(new Function<Long, Long>() {
                        @Override
                        public Long apply(Long aLong) throws Exception {
                            return countTime - aLong;// aLong从0开始
                        }
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<Long>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            mDisposable = d;
                        }

                        @Override
                        public void onNext(Long aLong) {
                            Log.e("onNext", "" + aLong);
                        }

                        @Override
                        public void onError(Throwable e) {
                        }

                        @Override
                        public void onComplete() {
                            requestTicket(false, true);
                            if (mDisposable != null) {
                                mDisposable.dispose();
                            }
                        }
                    });
        }
    }

    /**
     * 门票
     */
    public void requestTicket(boolean showFree, boolean save) {
        Map<String, String> map = new HashMap<>();
        HttpUtils.getInstance()
                .data(model.tickUserInfo(map), this,
                        new OnSuccessResult<TicketEntity>() {
                            @Override
                            public void onSuccessResult(BaseResponse<TicketEntity> response) {
                                if (YStringUtil.eq(2, response.getData().getWindowTicket())) {
                                    YActivityUtil.getInstance().jumpTicketDialog(showFree);
                                    if (save) YSPUtils.getInstance().saveTicketFree();
                                }
                                try {
                                    Log.e("门票是否购买", "" + response.getData().getWindowTicket());
                                } catch (Exception e) {
                                }
                            }
                        });
    }


    /**
     * 用户信息
     */
    public void requestUser() {
        Map<String, String> map = new HashMap<>();
        HttpUtils.getInstance()
                .data(model.user(map), this,
                        new OnSuccessResult<UserResult>() {
                            @Override
                            public void onSuccessResult(BaseResponse<UserResult> response) {
                                //如果是女号必须认证
                                if (YStringUtil.noEq(2, response.getData().getIsReal())
                                        && YUserUtil.isGirl()
                                        && !YChannelUtil.getInstance().beta()
                                        && YConfigUtil.isRealSwitch()
                                ) {
                                    YActivityUtil.getInstance().jumpRealDialog();
                                }
                            }
                        });
    }


}
